package com.change.core.util;

import com.change.core.dto.Poster;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.time.Instant;

/**
 * @author tongzhaomei
 * @version 1.0
 * @time 2022-06-08 10-52
 */
public class PosterUtil {

    public static Poster initPoster(Poster poster_) {
        Poster poster = new Poster();
        //画布
        poster.setWidth(poster_.getWidth());
        poster.setHeight(poster_.getHeight());
        //头像
        poster.setAvatarUrl(poster_.getAvatarUrl());
        poster.setCircle(true);
        poster.setAvatarX((int) (poster_.getWidth() / 11.5));
        poster.setAvatarY(poster_.getHeight() / 28);
        poster.setAvatarWidth(poster_.getWidth() / 6);
        poster.setAvatarHeight(poster_.getHeight() / 6);
        //名字
        poster.setName(poster_.getName());
        poster.setNameFont(new Font("微软雅黑", Font.PLAIN, poster_.getWidth() / 24));
        poster.setNameColor(new Color(33, 33, 33));
        poster.setNameX(poster.getAvatarX() + poster.getAvatarWidth() + 20);
        poster.setNameY(poster.getAvatarY() + poster.getAvatarHeight() / 2 + 15);
        //天气状态图片
        poster.setStatusUrl(poster_.getStatusUrl());
        poster.setStatusWidth(75);
        poster.setStatusHeight(80);
        poster.setStatusX((poster_.getWidth() - poster.getStatusWidth()) / 2);
        poster.setStatusY(poster.getAvatarY() + poster.getAvatarHeight());
        //时间
        poster.setCreateTime(poster_.getCreateTime());
        poster.setTimeColor(Color.black);
        poster.setTimeFont(new Font("微软雅黑", Font.PLAIN, 18));
        poster.setTimeX(60);
        poster.setTimeY(poster.getStatusY() + poster.getAvatarHeight());
        //温度
        poster.setTemperature(poster_.getTemperature());
        poster.setTemperatureColor(Color.BLACK);
        poster.setTemperatureFont(new Font("微软雅黑", Font.BOLD, 20));
        poster.setTemperatureWidth(120);
        poster.setTemperatureHeight(32);
        poster.setTemperatureX((poster_.getWidth() - poster.getStatusWidth()) / 2 + 5);
        poster.setTemperatureY(poster.getStatusY() + poster.getAvatarHeight() + 30);
        //描述
        poster.setDesc(poster_.getDesc());
        poster.setDescColor(Color.BLACK);
        poster.setDescFont(new Font("微软雅黑", Font.BOLD, 18));
        poster.setDescX((poster_.getWidth() - poster.getStatusWidth()) / 2 + 18);
        poster.setDescY(poster.getTemperatureY() + poster.getAvatarHeight() - 80);

        //小程序码
        poster.setQrCodeUrl(poster_.getQrCodeUrl());
        poster.setQrCodeWidth((int) (poster_.getWidth() / 2.85));
        poster.setQrCodeHeight((int) (poster_.getWidth() / 2.85));
        poster.setQrCodeX((int) (poster_.getWidth() / 16.5));
        poster.setQrCodeY(poster_.getHeight() - poster.getQrCodeHeight() - (int) (poster_.getHeight() / 7.68));
        //tips1
        poster.setTip1("长按识别小程序码");
        poster.setTip1Color(Color.BLACK);
        poster.setTip1Font(new Font("宋体", Font.BOLD, poster_.getWidth() / 21));
        poster.setTip1X(poster.getQrCodeX() + poster.getQrCodeWidth() + 20);
        poster.setTip1Y(poster.getQrCodeY() + poster.getQrCodeHeight() / 2 + 10);
        //footer
        poster.setFooterColor(new Color(49, 196, 141));
        poster.setFooterWidth(poster_.getWidth());
        poster.setFooterHeight(poster_.getHeight() / 13);
        poster.setFooterX(0);
        poster.setFooterY(poster_.getHeight() - poster.getFooterHeight());
        //footer tips
        poster.setFooterTip("「心觉咨询」提供内容及技术支持");
        poster.setFooterTipColor(Color.WHITE);
        poster.setFooterTipFont(new Font("宋体", Font.BOLD, poster_.getWidth() / 21));
        poster.setFooterTipX((poster_.getWidth() - (poster.getFooterTip().length() * poster_.getWidth() / 21)) / 2);
        poster.setFooterTipY(poster_.getHeight() - poster.getFooterHeight() / 3);
        return poster;
    }

    public static String drawPoster(Poster poster) throws Exception {
        long startTime = System.currentTimeMillis();
        String qrCodeUrl = poster.getQrCodeUrl();
        String statusUrl = poster.getStatusUrl();
        String avatarUrl = poster.getAvatarUrl();
        BufferedImage qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
        BufferedImage statusImage = ImageIO.read(new URL(statusUrl));
        int width = poster.getWidth();
        int height = poster.getHeight();
        //画布
        BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        g.setBackground(Color.WHITE);//设置背景色
        g.clearRect(0, 0, width, height);

        // 设置文字抗锯齿
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
        //圆形头像
        BufferedImage newAvatar = circle(avatarUrl, poster.getAvatarWidth());
        //画头像
        g.drawImage(newAvatar.getScaledInstance(newAvatar.getWidth(), newAvatar.getHeight(), Image.SCALE_SMOOTH), poster.getAvatarX(), poster.getAvatarY(), null);
        // 4. 写字（昵称）
        g.setColor(poster.getNameColor());
        g.setFont(poster.getNameFont());
        g.drawString(poster.getName(), poster.getNameX(), poster.getNameY());
        // 写入温度
        g.setColor(poster.getTemperatureColor());
        g.setFont(poster.getTemperatureFont());
        g.drawString(poster.getTemperature(), poster.getTemperatureX(), poster.getTemperatureY());
        // 写入时间
        g.setFont(poster.getTimeFont());
        g.setColor(poster.getTimeColor());
        g.drawString(poster.getCreateTime(), poster.getTimeX(), poster.getTimeY());

        //画商品
//       g.drawImage(Thumbnails.of(goodsImage).size(poster.getGoodsWidth(), poster.getGoodsHeight()).asBufferedImage(), poster.getGoodsX(), poster.getGoodsY(), null);
        g.drawImage(statusImage.getScaledInstance(poster.getStatusWidth(), poster.getStatusHeight(), Image.SCALE_SMOOTH), poster.getStatusX(), poster.getStatusY(), null);
        //描述
        g.setColor(poster.getDescColor());
        g.setFont(poster.getDescFont());
        g.drawString(poster.getDesc(), poster.getDescX(), poster.getDescY());

        //画小程序码
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);
        //画tips1
        g.setColor(poster.getTip1Color());
        g.setFont(poster.getTip1Font());
        g.drawString(poster.getTip1(), poster.getTip1X(), poster.getTip1Y());
        //画底部栏
        g.setColor(poster.getFooterColor());
        g.fillRect(poster.getFooterX(), poster.getFooterY(), poster.getFooterWidth(), poster.getFooterHeight());
        //画底部栏提示
        g.setColor(poster.getFooterTipColor());
        g.setFont(poster.getFooterTipFont());
        g.drawString(poster.getFooterTip(), poster.getFooterTipX(), poster.getFooterTipY());
        g.dispose();
        File resultImg = new File("data/image/weather/" + Instant.now().getEpochSecond() + ".png");
        if (!resultImg.exists()) {
            resultImg.mkdirs();
        }
        ImageIO.write(canvas, "png", resultImg);
        //上传服务器代码
        //ByteArrayOutputStream bs = new ByteArrayOutputStream();
        //ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
        //ImageIO.write(canvas, "png", imgOut);
        //InputStream inSteam = new ByteArrayInputStream(bs.toByteArray());
        //String url = OSSFactory.build().upload(inSteam, UUID.randomUUID().toString()+".png");
        System.out.println("生成成功！");
        System.out.println("耗时: " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
        System.out.println("生成文件路径: " + resultImg.getAbsolutePath());
        return resultImg.getAbsolutePath();
    }

    private static BufferedImage circle(String avatar_img, int width) throws Exception {
        BufferedImage avatar = ImageIO.read(new URL(avatar_img));
        BufferedImage newAvatar = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, width, width);
        Graphics2D g2 = newAvatar.createGraphics();
        newAvatar = g2.getDeviceConfiguration().createCompatibleImage(width, width, Transparency.TRANSLUCENT);
        g2 = newAvatar.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2 = newAvatar.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fillRoundRect(0, 0, width, width, width, width);
        g2.setComposite(AlphaComposite.SrcIn);
        g2.drawImage(avatar, 0, 0, width, width, null);
        g2.dispose();
        return newAvatar;
    }

    //文本换行处理
    public static String makeLineFeed(String zh, FontDesignMetrics metrics, int max_width) {
        StringBuilder sb = new StringBuilder();
        int line_width = 0;
        for (int i = 0; i < zh.length(); i++) {
            char c = zh.charAt(i);
            sb.append(c);
            // 如果主动换行则跳过
            if (sb.toString().endsWith("\n")) {
                line_width = 0;
                continue;
            }
            // FontDesignMetrics 的 charWidth() 方法可以计算字符的宽度
            int char_width = metrics.charWidth(c);
            line_width += char_width;
            // 如果当前字符的宽度加上之前字符串的已有宽度超出了海报的最大宽度，则换行
            if (line_width >= max_width - char_width) {
                line_width = 0;
                sb.append("\n");
            }
        }
        return sb.toString();
    }

}
